package com.xvyy.tingshu.album.service.impl;

import com.xvyy.tingshu.album.config.VodProperties;
import com.xvyy.tingshu.album.service.VodService;
import com.xvyy.tingshu.common.execption.TsException;
import com.xvyy.tingshu.common.util.UploadFileUtil;
import com.xvyy.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class VodServiceImpl implements VodService {

    @Autowired
    private VodProperties vodProperties;


    @Override
    public Map<String, Object> uploadTrack(MultipartFile file) {

        String mediaUrl = ""; // 视频的url
        String fileId = ""; // 视频的fileId
        String secretId = vodProperties.getSecretId(); // 密钥ID
        String secretKey = vodProperties.getSecretKey(); // 密钥KEY
        String region = vodProperties.getRegion();// 地域

        // TencentCloud官方文档 指定分片并发数https://cloud.tencent.com/document/product/266/10276
        // 1. 初始化一个上传客户端 VodUploadClient
        VodUploadClient client = new VodUploadClient(secretId, secretKey);
        // 2.构建上传请求对象
        VodUploadRequest request = new VodUploadRequest();
        //2.1 要上传文件的地址
        String tempPath = UploadFileUtil.uploadTempPath(vodProperties.getTempPath(), file);// 临时文件路径
        request.setMediaFilePath(tempPath);// 设置要上传文件的本地路径
        request.setConcurrentUploadNumber(5);// 对大文件起作用，并发上传的分片数

        try {
            // 3.获取上传后的视频信息，此处用的是同步上传
            VodUploadResponse response = client.upload(region, request);
            mediaUrl = response.getMediaUrl();
            fileId = response.getFileId();


            log.info("文件上传成功:{}", response.getFileId());
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("文件上传失败:{}", e.getMessage());
        }

        // 4.构建上传视频在vod的文件标识以及地址
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("mediaFileId", fileId);
        resultMap.put("mediaUrl", mediaUrl);
        return resultMap;
    }

    @Override
    public TrackMediaInfoVo getTrackMediaInfoVo(String mediaFileId) {

        String secretId = vodProperties.getSecretId(); // 密钥ID
        String secretKey = vodProperties.getSecretKey(); // 密钥KEY
        String region = vodProperties.getRegion();// 地域

        try {
            // 1. 实例化一个认证对象
            Credential cred = new Credential(secretId, secretKey);
            // 2. 实例化VOD的client对象
            VodClient client = new VodClient(cred, region);
            // 3. 实例化一个请求对象
            DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
            // 3.1 给请求对象设置参数
            String[] fileIds = {mediaFileId};
            req.setFileIds(fileIds);

            // 4. 得到VOD的响应
            DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);

            // 5. 输出json格式的字符串回包信息
            log.info("获取媒体信息成功:{}", AbstractModel.toJsonString(resp));

            // 6. 封装成我们的vo对象返回
            TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();
            MediaInfo[] mediaInfoSet = resp.getMediaInfoSet();
            if (mediaInfoSet != null && mediaInfoSet.length > 0) {
                MediaInfo mediaInfo = mediaInfoSet[0];
                MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                MediaMetaData metaData = mediaInfo.getMetaData();
                trackMediaInfoVo.setMediaUrl(basicInfo.getMediaUrl());
                trackMediaInfoVo.setType(basicInfo.getType());
                trackMediaInfoVo.setDuration(metaData.getDuration());
                trackMediaInfoVo.setSize(metaData.getSize());
            }

            return trackMediaInfoVo;

        } catch (TencentCloudSDKException e) {
            log.error("获取媒体信息失败:{}", e.getMessage());
        }

        return null;
    }

    @Override
    public void removeVodFile(String mediaFileId) {

        String secretId = vodProperties.getSecretId(); // 密钥ID
        String secretKey = vodProperties.getSecretKey(); // 密钥KEY
        String region = vodProperties.getRegion();// 地域
        try{
            // 实例化一个认证对象，密钥ID和密钥Key从环境变量获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个client对象
            VodClient client = new VodClient(cred, region);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            // 返回的resp
            DeleteMediaResponse resp = client.DeleteMedia(req);
            // 输出json格式的字符串回包
            log.info("删除视频成功:{}", AbstractModel.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.error("删除视频失败:{}", e.getMessage());
            //抛出异常，事务回滚
            throw new TsException(201, "删除视频失败");
        }
    }
}
